package cn.rengy.tpa.wxmp.wxapp.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.util.WeChatReturnCode;

public class Code2SessionApi {
	private static Logger logger = LoggerFactory.getLogger(Code2SessionApi.class);

	private static final String JSCODE2SESSIONURL="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&";
	
	public static Code2SessionResponse code2Session(String code,String appid,String appsecret){
		/**
		 * -1	系统繁忙，此时请开发者稍候再试
		0	请求成功
		40029	code 无效
		45011	频率限制，每个用户每分钟100次
		 */
        StringBuilder sb=new StringBuilder(JSCODE2SESSIONURL)
        		.append("appid=").append(appid)
        		.append("&secret=").append(appsecret)
        		.append("&js_code=").append(code);
        String url=sb.toString();
        int j=3;
		int max=j;
		for(;j>0&&max>0;max--){
			String jsonResult=HttpUtils.get(url);
	        JSONObject json = JSONObject.parseObject(jsonResult);
	        int errcode=json.getIntValue("errcode");
	        if(errcode==0) {
	        	String session_key = json.getString("session_key");
		        String openid =  json.getString("openid");
		        String unionid = json.getString("unionid");
		        return new Code2SessionResponse(openid,session_key,unionid);
			}else if(errcode==-1) {
				j--;
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
				}
			}else {
				String errMsg = WeChatReturnCode.getMsg(errcode,json.getString("errmsg"));
				throw new WeChatException(errcode,errMsg);
			}
		}
		throw new WeChatException("code2Session失败");
	}
}
